#!/usr/bin/env python3
"""
聊天记录导出工具
Chat Export Tool
"""

import os
import json
from datetime import datetime
import argparse

def create_chat_export_template():
    """创建聊天记录导出模板"""
    template = {
        "export_info": {
            "timestamp": datetime.now().isoformat(),
            "tool": "Cursor Chat Export",
            "version": "1.0"
        },
        "conversation": [
            {
                "role": "user",
                "timestamp": "2024-01-01T10:00:00",
                "content": "用户消息内容"
            },
            {
                "role": "assistant", 
                "timestamp": "2024-01-01T10:00:30",
                "content": "助手回复内容"
            }
        ]
    }
    
    return template

def export_to_markdown(chat_data, output_file):
    """导出为Markdown格式"""
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write("# 聊天记录导出 / Chat Export\n\n")
        f.write(f"**导出时间 / Export Time:** {chat_data['export_info']['timestamp']}\n\n")
        f.write("---\n\n")
        
        for i, msg in enumerate(chat_data['conversation'], 1):
            role = "🧑‍💻 用户" if msg['role'] == 'user' else "🤖 助手"
            f.write(f"## {i}. {role}\n")
            f.write(f"**时间:** {msg['timestamp']}\n\n")
            f.write(f"{msg['content']}\n\n")
            f.write("---\n\n")

def export_to_text(chat_data, output_file):
    """导出为纯文本格式"""
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write("聊天记录导出 / Chat Export\n")
        f.write("=" * 50 + "\n")
        f.write(f"导出时间 / Export Time: {chat_data['export_info']['timestamp']}\n\n")
        
        for i, msg in enumerate(chat_data['conversation'], 1):
            role = "用户" if msg['role'] == 'user' else "助手"
            f.write(f"[{i}] {role} ({msg['timestamp']}):\n")
            f.write(f"{msg['content']}\n")
            f.write("-" * 50 + "\n\n")

def main():
    parser = argparse.ArgumentParser(description='聊天记录导出工具')
    parser.add_argument('--input', '-i', help='输入的JSON文件路径')
    parser.add_argument('--output', '-o', help='输出文件路径')
    parser.add_argument('--format', '-f', choices=['markdown', 'text', 'json'], 
                       default='markdown', help='导出格式')
    parser.add_argument('--template', action='store_true', help='创建模板文件')
    
    args = parser.parse_args()
    
    if args.template:
        # 创建模板文件
        template = create_chat_export_template()
        template_file = 'chat_template.json'
        with open(template_file, 'w', encoding='utf-8') as f:
            json.dump(template, f, ensure_ascii=False, indent=2)
        print(f"模板文件已创建: {template_file}")
        print("请编辑此文件，然后使用 --input 参数导入")
        return
    
    if not args.input:
        print("请指定输入文件，或使用 --template 创建模板")
        return
    
    # 读取聊天数据
    try:
        with open(args.input, 'r', encoding='utf-8') as f:
            chat_data = json.load(f)
    except FileNotFoundError:
        print(f"文件未找到: {args.input}")
        return
    except json.JSONDecodeError:
        print(f"JSON格式错误: {args.input}")
        return
    
    # 确定输出文件名
    if args.output:
        output_file = args.output
    else:
        base_name = os.path.splitext(args.input)[0]
        ext = {'markdown': '.md', 'text': '.txt', 'json': '.json'}[args.format]
        output_file = f"{base_name}_export{ext}"
    
    # 导出
    if args.format == 'markdown':
        export_to_markdown(chat_data, output_file)
    elif args.format == 'text':
        export_to_text(chat_data, output_file)
    elif args.format == 'json':
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(chat_data, f, ensure_ascii=False, indent=2)
    
    print(f"聊天记录已导出到: {output_file}")

if __name__ == '__main__':
    main() 